import 'package:boss/color_constant.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:hi_common/hi_common.dart';
import 'package:flutter/material.dart';

class CheckBoxData<T> {
  String title;
  T value;

  CheckBoxData({this.title, this.value});
}

class CheckBox<T> extends StatefulWidget {
  final List<CheckBoxData<T>> items;
  final List<T> value;
  final ValueChanged<List<T>> onChanged;

  const CheckBox({
    Key key,
    @required this.items,
    this.value,
    this.onChanged,
  }) : super(key: key);

  @override
  _CheckBoxState<T> createState() => _CheckBoxState<T>();
}

class _CheckBoxState<T> extends State<CheckBox<T>> {
  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: widget.items.map((item) {
        var isSelected = widget.value.contains(item.value);
        return CheckBoxItem<T>(
          data: item,
          isSelected: isSelected,
          onTap: () {
            var copy = List<T>.from(widget.value);

            isSelected ? copy.remove(item.value) : copy.add(item.value);

            widget?.onChanged(copy);
          },
        );
      }).toList(),
    );
  }
}

class CheckBoxItem<T> extends StatelessWidget {
  final CheckBoxData<T> data;
  final VoidCallback onTap;
  final bool isSelected;

  const CheckBoxItem({
    Key key,
    this.data,
    this.onTap,
    this.isSelected = false,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        child: Row(
          children: <Widget>[
            Container(
              width: 20.w,
              height: 20.w,
              padding: EdgeInsets.all(
                5.w,
              ),
              decoration: BoxDecoration(
                border: Border.all(
                  color: ColorConstant.ffcc,
                  width: 1.px,
                ),
                borderRadius: BorderRadius.circular(
                  4.w,
                ),
              ),
              child: Container(
                color: isSelected ? ColorConstant.ff5770f6 : Colors.white,
              ),
            ),
            Container(
              margin: EdgeInsets.only(
                left: 10.w,
              ),
              child: Text(
                data.title,
                style: TextStyleConstant().normal_1_22,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
